package com.pactera.madp.cp.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pactera.madp.cp.api.entity.WorkContactEntity;
import com.pactera.madp.cp.api.vo.contact.ContactPageVO;
import com.pactera.madp.cp.handler.CorpContextHolder;
import com.pactera.madp.cp.mapper.ContactMapper;
import com.pactera.madp.cp.mapper.WorkContactMapper;
import com.pactera.madp.cp.service.IWorkContactEmployeeService;
import com.pactera.madp.cp.service.IWorkContactService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;

/**
 * @author zhaojinjian
 * @ClassName WorkContactServiceImpl.java
 * @Description TODO
 * @createTime 2020/12/7 17:56
 */
@Service
public class WorkContactServiceImpl extends ServiceImpl<ContactMapper, WorkContactEntity> implements IWorkContactService {

    @Resource
    private WorkContactMapper workContactMapper;
    @Resource
    private IWorkContactEmployeeService workContactEmployeeService;

    @Override
    public String getWXExternalUserid(int contactId) {
        WorkContactEntity workContactEntity = this.baseMapper.selectById(contactId);
        if (workContactEntity != null) {
            return workContactEntity.getWxExternalUserid();
        }
        return "";
    }

    /**
     * @description:企业外部联系人模糊匹配
     * @return:
     * @author: Huayu
     * @time: 2020/12/16 14:21
     */
    @Override
    public List<WorkContactEntity> getWorkContactsByCorpIdName(Integer corpId, String name, String clStr) {
        QueryWrapper<WorkContactEntity> workContactQueryWrapper = new QueryWrapper<WorkContactEntity>();
        workContactQueryWrapper.select(clStr);
        workContactQueryWrapper.eq("corp_id", corpId);
        workContactQueryWrapper.like("name", name);
        return this.baseMapper.selectList(workContactQueryWrapper);
    }

    @Override
    public WorkContactEntity getWorkContactsById(Integer contactId, String clStr) {
        QueryWrapper<WorkContactEntity> workContactQueryWrapper = new QueryWrapper<WorkContactEntity>();
        if (!clStr.equals("") || clStr != null) {
            workContactQueryWrapper.select(clStr);
        }
        return this.baseMapper.selectById(contactId);
    }

    @Override
    public List<WorkContactEntity> getWorkContactsByCorpId(Integer corpId, String clStr) {
        QueryWrapper<WorkContactEntity> workContactQueryWrapper = new QueryWrapper<WorkContactEntity>();
        workContactQueryWrapper.select(clStr);
        workContactQueryWrapper.eq("corp_id", corpId);
        return this.baseMapper.selectList(workContactQueryWrapper);
    }

    @Override
    public List<WorkContactEntity> getWorkContactByCorpIdWxExternalUserIds(Integer corpId, List<String> froms,List<String> tolists, String s) {
        List<String> list = new LinkedList<>();
        list.addAll(froms);
        list.addAll(tolists);
        QueryWrapper<WorkContactEntity> workContactQueryWrapper = new QueryWrapper<WorkContactEntity>();
        workContactQueryWrapper.select(s);
        workContactQueryWrapper.in("wx_external_userid",list);
        workContactQueryWrapper.eq("corp_id",corpId);
        return this.baseMapper.selectList(workContactQueryWrapper);
    }


    @Override
    public WorkContactEntity getWorkContactByWxExternalUserId(String externalUserId) {
        return this.getOne(Wrappers.<WorkContactEntity>lambdaQuery()
                .eq(WorkContactEntity::getWxExternalUserid,externalUserId)
                .eq(WorkContactEntity::getCorpId, CorpContextHolder.getCorpId()));
    }

    @Override
    public List<WorkContactEntity> selectAll(Integer corpId) {
        List<WorkContactEntity> workContactEntities = workContactMapper.selectAll(corpId);
        return workContactEntities;
    }

    @Override
    public Integer countByEmployeeIds(Set<Integer> employeeIds, Integer corpId, String today) {
        return this.baseMapper.countByEmployeeIds(employeeIds, corpId, today);
    }

    @Override
    public List<ContactPageVO> getWorkContactsByDeptId(Integer deptId) {
        return baseMapper.getWorkContactsByDeptId(deptId);
    }

    /*@Override
    public WorkContactDailyResp contact(String end){
        //企業id
        Integer corpId = CorpContextHolder.getCorpId();
        ArrayList<Integer> deFlags = new ArrayList<>();
        deFlags.add(1);
        deFlags.add(0);
        List<WorkContactEmployeeEntity> Entities = workContactEmployeeService.lambdaQuery()
                .eq(WorkContactEmployeeEntity::getCorpId, corpId)
                .in(WorkContactEmployeeEntity::getDelFlag, deFlags)
                .list();
        HashMap<String, Object> map;
        map = formData(end, new WorkContactDailyResp());
        WorkContactDailyResp workContactDailyResp = new WorkContactDailyResp();
        ArrayList<WorkContactDailyIndexResp> workContactDailyResps = new ArrayList<>();
        //保存前一天的客户数
        Integer lastTotal = 0;
        Object[] keys =  map.keySet().toArray();
        Arrays.sort(keys);
        for (Object key : keys) {
            //归纳数据
            WorkContactDailyIndexResp workContactDailyIndexResp = new WorkContactDailyIndexResp();
            //每日净增客戶
            Integer realAddNum = 0;
            //每日新增客戶數
            Integer addNum = 0;
            //每日客戶總數
            Integer total = 0;
            for (int i = 0; i < Entities.size(); i++) {
                WorkContactEmployeeEntity workContactEmployeeEntity = Entities.get(i);
                String createTime = workContactEmployeeEntity.getCreateTime().toLocalDate().toString();
                //入坑
                if (key.equals(createTime)) {
                    Integer contactId = workContactEmployeeEntity.getContactId();
                    Integer employeeId = workContactEmployeeEntity.getEmployeeId();
                    int size = workContactEmployeeService.lambdaQuery()
                            .eq(WorkContactEmployeeEntity::getContactId, contactId)
                            .eq(WorkContactEmployeeEntity::getEmployeeId, employeeId)
                            .eq(WorkContactEmployeeEntity::getDelFlag, 1)
                            .list().size();
                    if (size == 0) {
                        realAddNum++;
                    }
                }

                if (createTime.compareTo((String) key) <= 0) {
                     total++;
                }
            }
            addNum = total - lastTotal;
            lastTotal = total;
            workContactDailyIndexResp.setTime((String) key);
            workContactDailyIndexResp.setRealAddNum(realAddNum);
            workContactDailyIndexResp.setAddNum(addNum);
            workContactDailyIndexResp.setTotal(total);
            workContactDailyResps.add(workContactDailyIndexResp);
        }
        List<WorkContactDailyIndexResp> newSortList = workContactDailyResps.stream().sorted(Comparator.comparing(WorkContactDailyIndexResp::getTime).reversed())
                .collect(Collectors.toList());
        newSortList.remove(7);
        WorkContactDailyIndexResp workContactDailyIndexResp = newSortList.get(0);
        workContactDailyResp.setTotal(workContactDailyIndexResp.getTotal());
        workContactDailyResp.setRealAddNum(workContactDailyIndexResp.getRealAddNum());
        workContactDailyResp.setAddNum(workContactDailyIndexResp.getAddNum());
        workContactDailyResp.setList(null);
        return workContactDailyResp;
    }

    private HashMap<String, Object> formData(String end, Object obj) {
        if (obj instanceof WorkContactDailyResp) {
            obj = new WorkContactDailyResp();
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar date = Calendar.getInstance();
        Map<String, Object> map = new HashMap<String, Object>();

        if (end != null) {//按天统计
            try {
                date.setTime(sdf.parse(end));
            } catch (ParseException e) {
                e.printStackTrace();
            }
            date.add(Calendar.DAY_OF_YEAR, -1);
            for (int i = 1; i <= 8; i++) {
                map.put(sdf.format(date.getTime()), obj);
                date.add(Calendar.DAY_OF_YEAR, -1);
            }
        } else {
            date.setTime(new Date());
            date.add(Calendar.DAY_OF_YEAR, -1);
            date.set(Calendar.HOUR_OF_DAY, 0);
            date.set(Calendar.MINUTE, 0);
            date.set(Calendar.SECOND, 0);
            date.set(Calendar.MILLISECOND, 0);
            for (int i = 1; i <= 8; i++) {
                map.put(sdf.format(date.getTime()), obj);
                date.add(Calendar.DAY_OF_YEAR, -1);
            }
        }
        return (HashMap<String, Object>) map;
    }*/

}
